package com.mallbook.controller.filter;

import com.mallbook.model.pojo.User;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-13
 * 中文乱码
 */
@WebFilter("/*")
public class FormatFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(FormatFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("进入FormatFilter过滤器");
        HttpServletRequest req = (HttpServletRequest) request;
        logger.info("URL:" + req.getRequestURL());
        logger.info("QS:" + req.getQueryString());
        HttpServletResponse resp = (HttpServletResponse) response;
        // TODO: 2022-07-13 中文乱码
//        resp.setContentType("text/html");
//        resp.setCharacterEncoding("utf-8");
//        req.setCharacterEncoding("utf-8");

        String uri = req.getRequestURI();
        if (uri.contains("/ucenter/")) {
            logger.info("未登录访问个人中心");
            Object adminList = req.getSession().getAttribute("USER");
            if (adminList != null) {
                chain.doFilter(req, resp);
            } else {
                resp.sendRedirect("/user?opr=login"); // 转到登录界面
            }
        } else if (uri.contains("/index") || uri.contains("/") || uri.contains("/goods") || uri.contains("/captcha") || uri.contains("/user") || uri.contains("/css/") || uri.contains("/goodsImg/") || uri.contains("/images/") || uri.contains("/js/") || uri.contains("/layer/") || uri.contains("/ueditor/") || uri.contains("/userImg/")) {
            chain.doFilter(req, resp);
        } else {
            Object adminList = req.getSession().getAttribute("USER");
            if (adminList != null) {
                chain.doFilter(req, resp);
            } else {
                resp.sendRedirect("/user?opr=login"); // 转到登录界面
            }
        }
    }

    @Override
    public void destroy() {

    }
}
